package com.miracle.basemvp.network.download;

import com.miracle.basemvp.util.FileUtils;

import org.reactivestreams.Subscriber;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class RetrofitClient {
    private static RetrofitClient mInstance;
    private static Retrofit retrofit;
    private static ProgressDownloadListener mDownloadListener;

    private RetrofitClient(ProgressDownloadListener listener) {
        retrofit = RetrofitBuilder.buildRetrofit(listener);
    }

    /**
     * 获取RetrofitClient实例.
     *
     * @return 返回RetrofitClient单例
     */
    public static synchronized RetrofitClient getInstance(ProgressDownloadListener listener) {
        if (mInstance == null) {
            mDownloadListener = listener;
            mInstance = new RetrofitClient(listener);
        }
        return mInstance;
    }

    private <T> T create(Class<T> clz) {
        return retrofit.create(clz);
    }
//
//    /**
//     * 多文件上传.
//     *
//     * @param url 上传接口地址
//     * @param files 文件列表
//     * @param fileUploadObserver 文件上传回调
//     */
//    public void upLoadFiles(String url, List<File> files,
//                            FileUploadObserver<ResponseBody> fileUploadObserver) {
//        create(FileApi.class)
//                .uploadFile(url, MultipartBuilder.filesToMultipartBody(files,
//                        fileUploadObserver))
//                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                .subscribe(fileUploadObserver);
//
//    }

    public void downloadFiles(String url, Consumer<InputStream> consumer, String path) {
        create(FileApi.class)
                .download(url)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, InputStream>() {

                    @Override
                    public InputStream apply(ResponseBody responseBody) throws Exception {
                        return responseBody.byteStream();
                    }
                })
                .observeOn(Schedulers.computation())
                .doOnNext(new Consumer<InputStream>() {
                    @Override
                    public void accept(InputStream inputStream) throws Exception {
                        FileUtils.writeFile(inputStream, path, mDownloadListener);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer);
    }


}
